package com.lleice.web.handler;

import java.time.LocalDateTime;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lleice.web.utils.RequestHolder;

/**
 * 公共字段自动填充
 * @author lilizihao
 *
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler{
	
	private final static String CREATE_BY = "createBy";
	private final static String UPATE_BY = "updateBy";
	private final static String CREATE_TIME = "createTime";
	private final static String UPDATE_TIME = "updateTime";
	private final static String IS_ENABLE = "isEnable";
	private final static String IS_DELETE = "isDelete";
	private final static String DEFAULT_CREATE_BY = "系统添加";
	private final static String DEFAULT_UPDATE_BY = "系统更新";
	
	
	@Override
	public void insertFill(MetaObject arg0) {
        if(arg0.hasSetter(CREATE_BY)) {
        	if(RequestHolder.getCurrentUser() != null) {
        		this.setFieldValByName(CREATE_BY, RequestHolder.getCurrentUser().getUserName(), arg0);
        	}else {
        		this.setFieldValByName(CREATE_BY, DEFAULT_CREATE_BY, arg0);
        	}
        }
		if(arg0.hasSetter(CREATE_TIME)) {
			this.setFieldValByName(CREATE_TIME, LocalDateTime.now(), arg0);
		}
		if(arg0.hasSetter(UPDATE_TIME)) {
			//mybatis plus 这里有个bug 如果原来的字段有值的话 这里会覆盖原来的值
			if(arg0.getValue(UPDATE_TIME) == null) {
				this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), arg0);
			}
		}
		if(arg0.hasSetter(UPATE_BY)) {
			if(RequestHolder.getCurrentUser() != null) {
				this.setFieldValByName(UPATE_BY, RequestHolder.getCurrentUser().getUserName(), arg0);
			}else {
				this.setFieldValByName(UPATE_BY, DEFAULT_UPDATE_BY, arg0);
			}
		}
		if(arg0.hasSetter(IS_ENABLE)) {
			this.setFieldValByName(IS_ENABLE, 0, arg0);
		}
		if(arg0.hasSetter(IS_DELETE)) {
			this.setFieldValByName(IS_DELETE, 0, arg0);
		}
	}

	@Override
	public void updateFill(MetaObject arg0) {
		if(arg0.hasSetter(UPATE_BY)) {
			if(RequestHolder.getCurrentUser() != null) {
				this.setFieldValByName(UPATE_BY, RequestHolder.getCurrentUser().getUserName(), arg0);
			}else {
				this.setFieldValByName(UPATE_BY, DEFAULT_UPDATE_BY, arg0);
			}
		}
		if(arg0.hasSetter(UPDATE_TIME)) {
			this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), arg0);
		}
	}

}
